package cn.fzkj.gulimall.product.service.impl;

import cn.fzkj.common.constant.ProductConstant;
import cn.fzkj.gulimall.product.dao.*;
import cn.fzkj.gulimall.product.entity.AttrAttrgroupRelationEntity;
import cn.fzkj.gulimall.product.entity.AttrGroupEntity;
import cn.fzkj.gulimall.product.entity.CategoryEntity;
import cn.fzkj.gulimall.product.service.CategoryService;
import cn.fzkj.gulimall.product.vo.AttrRespVO;
import cn.fzkj.gulimall.product.vo.AttrVO;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.fzkj.common.utils.PageUtils;
import cn.fzkj.common.utils.Query;

import cn.fzkj.gulimall.product.entity.AttrEntity;
import cn.fzkj.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private AttrGroupDao groupDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public boolean saveAttr(AttrVO attr) {
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attr, entity);
        // 保存属性信息
        this.save(entity);
        // 基本属性才保存关联信息
        if (attr.getAttrType() == ProductConstant.AttrEnum.BASE_ATTR.getCode()){
            // 保存属性分组关联信息
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(entity.getAttrId());
            attrAttrgroupRelationDao.insert(relationEntity);
        }

        return true;
    }

    /**
     * 查询属性信息
     * @param catlogId
     * @param params
     * @param attrType 用来标识查询是销售属性还是基本属性
     * @return
     */
    @Override
    public PageUtils queryAttrPage(Long catlogId, Map<String, Object> params, String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("attr_type", "base".equalsIgnoreCase(attrType) ? ProductConstant.AttrEnum.BASE_ATTR.getCode() : ProductConstant.AttrEnum.SALE_ATTR.getCode());
        if (catlogId != null && catlogId != 0){
            queryWrapper.eq("catelog_id", catlogId);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            queryWrapper.and(wrapper -> {
                wrapper.like("attr_name", key).or().eq("attr_id", key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        List<Object> pages = page.getRecords().stream().map((attrEntity) -> {

            // TODO 数据库压力会不会太大？？？？
            AttrRespVO respVO = new AttrRespVO();
            BeanUtils.copyProperties(attrEntity, respVO);

            if (ProductConstant.AttrEnum.BASE_ATTR.getCode() == attrEntity.getAttrType()){
                AttrAttrgroupRelationEntity attrId = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (attrId != null) {
                    AttrGroupEntity entity = groupDao.selectById(attrId.getAttrGroupId());
                    if (entity != null){
                        respVO.setGroupName(entity.getAttrGroupName());
                    }
                }
            }
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                respVO.setCatelogName(categoryEntity.getName());
            }
            return respVO;

        }).collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(pages);
        return pageUtils;
    }

    @Override
    public AttrRespVO getAttrInfo(Long attrId) {
        AttrRespVO respVO = new AttrRespVO();
        AttrEntity attrEntity = this.getById(attrId);
        if (attrEntity != null){
            BeanUtils.copyProperties(attrEntity, respVO);
            Long[] categoryPath = categoryService.findCategoryPath(attrEntity.getCatelogId());

            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));

            if (relationEntity != null){
                respVO.setAttrGroupId(relationEntity.getAttrGroupId());
            }
            respVO.setCatelogPath(categoryPath);
        }
        return respVO;
    }

    /**
     * 更新属性信息，包括所属分组信息
     * @param attr
     * @return
     */
    @Transactional
    @Override
    public boolean updateAttr(AttrVO attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);

        this.updateById(attrEntity);

        // 更新关联的分组信息

        if (ProductConstant.AttrEnum.BASE_ATTR.getCode() == attr.getAttrType()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            Long count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count > 0) {
                // 更新
                attrAttrgroupRelationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                // 新增
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }
        return true;
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_group_id", attrGroupId));

        List<Long> attrIds = relationEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
        if (attrIds.size() == 0){
            return Collections.emptyList();
        }
        return this.listByIds(attrIds);

    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {

        if (CollectionUtils.isEmpty(attrIds)){
            return new ArrayList<>();
        }
        List<AttrEntity> attrEntities = baseMapper.selectList(
                new QueryWrapper<AttrEntity>().in("attr_id", attrIds)
                        .eq("search_type", 1)
        );
        return attrEntities.stream().map(attrEntity -> attrEntity.getAttrId()).collect(Collectors.toList());
    }

    /**
     * 查询没有被关联的属性
     * @param attrGroupId
     * @param params
     * @return
     */
    @Override
    public PageUtils getNoRelationAttrPage(Long attrGroupId, Map<String, Object> params) {
        AttrGroupEntity attrGroupEntity = groupDao.selectById(attrGroupId);
        Long catelogId = null;
        if (attrGroupEntity != null){
            catelogId = attrGroupEntity.getCatelogId();
        }
        // 查询当前分类下的其他分组
        List<AttrGroupEntity> attrGroupEntityList = groupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));

        List<Long> collect = attrGroupEntityList.stream().map(item -> item.getAttrGroupId()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)){
            return null;
        }
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        List<Long> attrIds = relationEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());


        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId);
        if (!CollectionUtils.isEmpty(attrIds)){
            wrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            wrapper.and(w->{
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

}